package com.cmb.service.dto;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.alibaba.fastjson.JSON;
import com.cmb.dto.TableColumnInfo;
import lombok.extern.slf4j.Slf4j;
import net.minidev.json.JSONUtil;

import java.io.BufferedWriter;
import java.io.FileWriter;

import static com.cmb.constant.CreateTableConstant.*;
import static com.cmb.constant.JavaFileConstant.createSingleColumnSql;

@Slf4j
public class AnalyseTableExcelListener implements ReadListener<TableColumnInfo> {

    private static StringBuilder COLUMN_SQL = new StringBuilder();

    // 可以尝试去获取云效插件上的工号
    private String fileName;

    private static StringBuilder COMMNET_SQL = new StringBuilder();

    private static StringBuilder SEQ_SQL = new StringBuilder();

    private String tableName;


    @Override
    public void invoke(TableColumnInfo tableColumnInfo, AnalysisContext analysisContext) {
        if ("表名称".equals(tableColumnInfo.getZhColumnName())) {
            tableName = tableColumnInfo.getEnColumnName();
            fileName = String.format(FILE_NAME, tableColumnInfo.getEnColumnName());
            String comment = String.format(COMMENT_TABLE_SQL, tableColumnInfo.getEnColumnName(), tableColumnInfo.getColumnLength());
            COMMNET_SQL.append(comment);
            return;
        }
        // 暂时不实现第二行内容
        if ("负责人".equals(tableColumnInfo.getZhColumnName()) || "字段中文名称".equals(tableColumnInfo.getZhColumnName())) {
            return;
        }

        // 第三行是创建索引行
        if ("主键名称".equals(tableColumnInfo.getZhColumnName())) {
            String createSeq = String.format(CREATE_SEQ_SQL, tableColumnInfo.getEnColumnName(), tableColumnInfo.getColumnLength());
            SEQ_SQL.append(createSeq);
            return;
        }
        String singleColumnSql = createSingleColumnSql(tableColumnInfo);
        COLUMN_SQL.append(singleColumnSql);
        String comment = String.format(COMMENT_COLUMN_SQL, tableColumnInfo.getEnColumnName(), tableColumnInfo.getZhColumnName());
        COMMNET_SQL.append(comment);

    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {

        String property = System.getProperty("user.dir");
        String filePath = property + "/src/main/resources" + "/" + fileName;

        try (BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(filePath))) {
            String createSql = String.format(CREATE_SQL, tableName, COLUMN_SQL.toString() + SEQ_SQL);
            bufferedWriter.write(createSql);
            bufferedWriter.newLine();

            bufferedWriter.write(COMMNET_SQL.toString());
            bufferedWriter.newLine();

            bufferedWriter.write(String.format(GRANT_SQL, tableName, tableName, tableName));
        } catch (Exception e) {
            log.error("创建文件出问题{}", e.getMessage());
        }
    }
}
